import { Suspense } from 'react'
import { Outlet, useLocation, useNavigate } from 'react-router-dom'
import { useDispatch, useSelector } from 'react-redux'
import type { RootState } from '../../store'
import { set as setUserInfo } from '../../store/userInfo'
import { set as setToken } from '../../store/token'
import { Dropdown, Layout, Menu, Space } from 'antd'
import { DownOutlined } from '@ant-design/icons'
import Loading from '../../components/Loading'
import getRoutes from '../../router'

import logo from '../../assets/logo.png'
import './index.scss'

const { Sider: LayoutSider, Content: LayoutContent, Header: LayoutHeader } = Layout

function PageHeader() {
  const nav = useNavigate()
  const userInfo = useSelector((state: RootState) => state.userInfo)
  const dispatch = useDispatch()

  return (
    <div className="header">
      <div className="header-left">
        <img src={logo} alt="" className="logo" />
      </div>
      <div className="header-right">
        <Space direction="vertical">
          <Dropdown
            menu={{
              items: [
                {
                  key: '1',
                  label: (
                    <div
                      onClick={() => {
                        dispatch(setUserInfo(null))
                        dispatch(setToken(''))
                        nav('/login')
                      }}
                    >
                      退出
                    </div>
                  )
                }
              ]
            }}
            placement="bottomRight"
          >
            <span className="username">
              {userInfo?.name}
              &nbsp;
              <DownOutlined />
            </span>
          </Dropdown>
        </Space>
      </div>
    </div>
  )
}

function PageMenu() {
  const location = useLocation()
  const nav = useNavigate()
  const key = location.pathname

  const userInfo = useSelector((state: RootState) => state.userInfo)

  function onClick(e: { key: string }) {
    if (key === e.key) return
    nav(e.key)
  }
  return (
    <Menu
      onClick={onClick}
      selectedKeys={[key]}
      mode="inline"
      items={getRoutes(userInfo?.role).map(({ path, meta }) => {
        return {
          label: meta.title,
          key: path,
          icon: <meta.Icon />
        }
      })}
    />
  )
}

function Admin() {
  return (
    <Layout>
      <LayoutHeader>
        <PageHeader></PageHeader>
      </LayoutHeader>
      <Layout>
        <LayoutSider>
          <PageMenu></PageMenu>
        </LayoutSider>
        <LayoutContent>
          <div className="container">
            <Suspense fallback={<Loading />}>
              <Outlet />
            </Suspense>
          </div>
        </LayoutContent>
      </Layout>
    </Layout>
  )
}

export default Admin
